package org.bocs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.Resource;
import org.bocs.dao.UserDao;
import org.bocs.entity.User;
import org.bocs.service.UserService;
import org.bocs.untils.JwtHelper;
import org.bocs.untils.MD5Util;
import org.bocs.untils.ResultVo;
import org.bocs.untils.StateCode;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

@Service
@Scope("singleton")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Transactional
    public ResultVo userRegister(String username, String password){
        synchronized (this) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            User user = userDao.selectOne(queryWrapper);
            if(user == null) {
                String md5 = MD5Util.md5(password);
                user = new User();
                user.setUsername(username);
                user.setPassword(md5);
                user.setUserImg("img/default.png");
                user.setUserRegtime(new Date());
                user.setUserModtime(new Date());
                int insert = userDao.insert(user);
                if(insert > 0) {
                    return new ResultVo(StateCode.SUCCESS, "注册成功", null);
                } else {
                    return new ResultVo(StateCode.FAIL, "注册失败", null);
                }

            } else {
                return new ResultVo(StateCode.FAIL, "用户已被注册", null);
            }
        }
    }

    @Override
    public ResultVo userLogin(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userDao.selectOne(queryWrapper);
        if(user == null) {
            return new ResultVo(StateCode.FAIL, "登录失败，用户名不存在", null);
        } else {
            String mdPwd = MD5Util.md5(password);
            if(mdPwd.equals(user.getPassword())) {
                String token = JwtHelper.createToken(user.getUserId(), password);
                return new ResultVo(StateCode.SUCCESS, token, user);
            } else {
                return new ResultVo(StateCode.FAIL, "登录失败，密码错误", null);
            }
        }
    }
}
